package com.xinhe.web.util;

public class Snowflake {
    private static final long EPOCH = 1620000000000L; // 设置一个特定的起始时间戳，如2021-05-03 00:00:00
    private static final long WORKER_ID_BITS = 5L;
    private static final long SEQUENCE_BITS = 12L;
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
    private static final long WORKER_ID = 1L; // 设置一个唯一的worker id

    private static long lastTimestamp = System.currentTimeMillis();

    private static long sequence = 0L;

    public static void main(String[] args) {
        long id = generateId();
        System.out.println("Generated ID: " + id);
    }

    public static synchronized Long generateId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Invalid system clock!");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;

            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        Long id = ((timestamp - EPOCH) << (WORKER_ID_BITS + SEQUENCE_BITS)) | (WORKER_ID << SEQUENCE_BITS) | sequence;

        return id;
    }

    private static long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}
